package com.woniushop.utils;

import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 将表单数据包装为实体对象
 * 
 * @author 崔新雄
 *
 */
public class ControllerUtils {

	/**
	 * 将数据包装成对象
	 * 
	 * @param map
	 * @param c
	 * @return
	 */
	public static Object mapToObject(Map<String, String[]> map, Class<?> c) {
		Object obj = null;
		// 获得所有属性
		Field[] fields = c.getDeclaredFields();
		try {
			obj = c.newInstance();
			for (Field field : fields) {
				// 获得属性名和属性类型
				String fieldName = field.getName();
				Class<?> fieldType = field.getType();
				// 以该属性名作为键，获得表单中对应的数据
				String[] values = map.get(fieldName);
				if (values != null && values.length != 0) {
					// 根据属性名获得对应的set方法名
					String methodName = "set" + toUpprFirst(fieldName);
					// 创建对应的set方法对象
					Method m = c.getMethod(methodName, fieldType);
					// 根据不同的参数类型调用不同的方法
					if (fieldType == String.class) {
						m.invoke(obj, values[0]);
					} else if (fieldType == Integer.class) {
						m.invoke(obj, Integer.parseInt(values[0]));
					} else if (fieldType == BigDecimal.class) {
						m.invoke(obj, new BigDecimal(values[0]));
					} else if (fieldType == Date.class) {
						m.invoke(obj, new SimpleDateFormat("yyyy-MM-dd hh-mm-ss").parse(values[0]));
					}
				}
			}
		} catch (InstantiationException | IllegalAccessException e) {
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			e.printStackTrace();
		} catch (SecurityException e) {
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return obj;
	}

	/**
	 * 返回JSON
	 * 
	 * @param map
	 * @param response
	 * @throws JsonGenerationException
	 * @throws JsonMappingException
	 * @throws IOException
	 */
	public static void returnJson(Map<String, Object> map, HttpServletResponse response)
			throws JsonGenerationException, JsonMappingException, IOException {
		PrintWriter writer = response.getWriter();
		ObjectMapper objectMapper = new ObjectMapper();
		objectMapper.writeValue(writer, map);
		writer.flush();
		writer.close();
	}

	/**
	 * 首字母大写
	 * 
	 * @param str
	 * @return
	 */
	private static String toUpprFirst(String str) {
		char[] chars = str.toCharArray();
		chars[0] = (char) (chars[0] - 32);
		str = new String(chars);
		return str;
	}
	
}
